import Vue from 'vue'
import App from './App'

import api from './common/api.js'
import TIM from 'tim-wx-sdk';
import giveGiftPopup from '@/components/give-gift-popup/give-gift-popup.vue'
import giftPopup from '@/components/gift-popup/gift-popup.vue'

Vue.config.productionTip = false

Vue.prototype.$api = api
Vue.prototype.TIM = TIM

Vue.component('give-gift-popup', giveGiftPopup)
Vue.component('gift-popup', giftPopup)

App.mpType = 'app'

const app = new Vue({
	...App
})
// uni.removeStorageSync('isLeaving');
// uni.removeStorageSync('device_code');
// uni.removeStorageSync('myInfo');
let myInfo = null;
// 极光推送
let jyJPush = uni.requireNativePlugin('JY-JPush');
try {
	myInfo = uni.getStorageSync('myInfo');
} catch (e) {
	console.log('获取本地存储myInfo失败', e);
}
// uni.showLoading({
// 		title: ''
// 	})

api.api.ajaxData({
	method: 'V1.Util'
}, res => {
	uni.hideLoading();
	if (res.code === 200) {
		Vue.prototype.QINIUURL = !!res.data.QinuURL ? res.data.QinuURL : ''
		Vue.prototype.QINUUPLOADURL = !!res.data.QinuUploadURL ? res.data.QinuUploadURL : ''
		Vue.prototype.AMAPKEY = !!res.data.AmapKey ? res.data.AmapKey : ''
		Vue.prototype.IDBEFORE = !!res.data.IDBefore ? res.data.IDBefore : ''
		Vue.prototype.ShareBg = !!res.data.ShareBg ? res.data.ShareBg : ''
		if (!!res.data.IMSdkAppID) {
			Vue.prototype.IMSDKAPPID = res.data.IMSdkAppID
		} else {
			Vue.prototype.IMSDKAPPID = ''
			uni.showToast({
				title: 'IMSdkAppID已过期',
				position: 'bottom',
				icon: 'none'
			})
			return false;
		}
		uni.setStorage({
			key: 'configInfo',
			data: {
				QINIUURL: app.QINIUURL,
				QINUUPLOADURL: app.QINUUPLOADURL,
				AMAPKEY: app.AMAPKEY,
				IDBEFORE: app.IDBEFORE,
				IMSDKAPPID: app.IMSDKAPPID,
				ShareBg: app.ShareBg,
			},
			success: res => {
				console.log('configInfo已存储')
			}
		})
		let tim = TIM.create({
			SDKAppID: app.IMSDKAPPID
		});
		tim.setLogLevel(1);
		tim.on(TIM.EVENT.SDK_READY, function(event) {
			// 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
			// event.name - TIM.EVENT.SDK_READY
			console.log('==========>TIM.EVENT.SDK_READY SDK已准备好');
			try {
				myInfo = uni.getStorageSync('myInfo');
				if (myInfo) {
					const sexList = [TIM.TYPES.GENDER_UNKNOWN, TIM.TYPES.GENDER_MALE, TIM.TYPES.GENDER_FEMALE];
					tim.updateMyProfile({
						nick: myInfo.name,
						avatar: myInfo.avatar,
						gender: sexList[myInfo.sex],
						allowType: TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
					}).then(imResponse => {
						console.log('更新资料成功:', imResponse.data);
						// 极光推送设置别名
						jyJPush.setJYJPushAlias(
							{
								userAlias: 'user_' + myInfo.lid
							},
							result => {}
						);
					}).catch(imError => {
						console.warn('更新资料失败:', imError);
					});
				}
			} catch (e) {
				console.log('获取本地存储myInfo失败', e);
			}
		});
		tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event) {
			// 收到推送的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
			// event.name - TIM.EVENT.MESSAGE_RECEIVED
			// event.data - 存储 Message 对象的数组 - [Message]
			console.log('收到推送的新消息', JSON.stringify(event.data))
			for (let i = 0; i < event.data.length; i++) {
				if (event.data[i].type == 'TIMCustomElem') {
					let now = new Date().getTime();
					let sendTime = event.data[i].time * 1000
					switch (event.data[i].payload.data) {
						case 'closeMic': // 拉下麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							if (now - sendTime < 30000) {
								uni.$emit('live_room-page', {
									type: event.data[i].payload.data,
									data: event.data[i]
								})
							}
							break;
						case 'ApplicationJoin': // 申请专属上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							if (now - sendTime < 30000) {
								uni.$emit('live_room-page', {
									type: event.data[i].payload.data,
									data: event.data[i]
								})
							}
							break;
						case 'AgreeJoin': // 同意专属上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							console.log('**************************')
							if (now - sendTime < 30000) {
								if (myInfo) {
									let info = JSON.parse(event.data[i].payload.extension)
									uni.showModal({
										title: '提示',
										content: info.anchor.name + '同意了您的上麦申请',
										success: res => {
											if (res.confirm) {
												uni.showLoading({
													title: ''
												});
												api.api.ajaxData({
													method: 'V1.LoveStart',
													uid: myInfo.id,
													token: myInfo.token,
													rid: info.roomid
												}, res => {
													uni.hideLoading();
													uni.showToast({
														title: res.msg,
														position: 'bottom',
														icon: 'none'
													});
													if (res.status) {
														tim.joinGroup({
															groupID: app.IDBEFORE + info.roomid,
															type: TIM.TYPES.GRP_AVCHATROOM,
														}).then(imResponse => {
															console.log('------>申请加群', imResponse.data)
														}).catch(imError => {
															console.warn('------>申请加群失败', imError);
														});
														let custom_ext = {
															roomid: info.roomid,
															id: myInfo.id,
															name: myInfo.name,
															avatar: myInfo.avatar,
															sex: myInfo.sex,
															age: myInfo.age,
															city: myInfo.city
														}
														let message = tim.createCustomMessage({
															to: app.IDBEFORE + info.anchor.id,
															conversationType: TIM.TYPES.CONV_C2C,
															payload: {
																data: 'Joined',
																description: '上麦成功',
																extension: JSON.stringify(custom_ext)
															}
														});
														tim.sendMessage(message).then(imResponse => {
															console.log('------>上麦成功', imResponse);
														}).catch(imError => {
															console.warn('------>上麦失败', imError);
														});
														getApp().globalData.invite_list = res.data.list;
														let live = {
															room: {
																id: res.data.rome.id,
																name: res.data.rome.name,
															},
															character: 'audience',
															gift: {
																id: res.data.gift.id,
																name: res.data.gift.name,
																file: res.data.gift.file,
																rose: res.data.gift.rose
															},
															anchor: {
																id: res.data.rome.user.id,
																name: res.data.rome.user.name,
																avatar: res.data.rome.user.avatar,
																sex: res.data.rome.user.sex,
																age: res.data.rome.user.age,
																city: res.data.rome.user.city,
															},
															url: res.data.play,
															minute: res.data.minute,
															type: res.data.rome.type,
														}
														uni.navigateTo({
															url: '../live/live_room?live=' + encodeURIComponent(JSON.stringify(live))
														});
													}
												})
											}
										}
									});
								}
							}
							break;
						case 'Joined': // 已上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							if (now - sendTime < 30000) {
								uni.$emit('live_room-page', {
									type: event.data[i].payload.data,
									data: event.data[i]
								})
							}
							break;
						case 'KickedOut': // 主播踢人
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'LovePrivate': // 邀请专属上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							if (now - sendTime < 30000) {
								setTimeout(() => {
									let pages = getCurrentPages();
									let page = pages[pages.length - 1];
									if (page.route != 'pages/invite/invite') {
										uni.navigateTo({
											url: '../invite/invite?type=private&inviteInfo=' + encodeURIComponent(event.data[i].payload.extension)
										})
									}
								}, 600)
							}
							break;
						case 'LivePublic': // 邀请非专属进房间
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							if (now - sendTime < 30000) {
								setTimeout(() => {
									let pages = getCurrentPages();
									let page = pages[pages.length - 1];
									if (page.route != 'pages/invite/invite') {
										uni.navigateTo({
											url: '../invite/invite?type=public&inviteInfo=' + encodeURIComponent(event.data[i].payload.extension)
										})
									}
								}, 600)
							}
							break;
						case 'LiveSevenRoom': // 邀请七人交友进房间
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							if (now - sendTime < 30000) {
								setTimeout(() => {
									let pages = getCurrentPages();
									let page = pages[pages.length - 1];
									if (page.route != 'pages/invite/invite') {
										uni.navigateTo({
											url: '../invite/invite?type=seven&inviteInfo=' + encodeURIComponent(event.data[i].payload.extension)
										})
									}
								}, 600)
							}
							break;
						case 'joinAnchor': // 申请非专属上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'AgreeJoinAnchor': // 申请非专属上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'AgreeJoinAnchor1': // 申请非专属上麦
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'gift':
							if (event.data[i].conversationType == 'GROUP') {
								tim.setMessageRead({
									conversationID: event.data[i].conversationID,
								});
								uni.$emit('live_room-page', {
									type: event.data[i].payload.data,
									data: event.data[i]
								})
							}
							uni.$emit('message-page', {
								type: 'message',
								data: event.data[i]
							})
							uni.$emit('im-page', {
								type: 'message',
								data: event.data[i]
							})
							break;
						case 'like':
							uni.$emit('message-page', {
								type: 'message',
								data: event.data[i]
							})
							break;
						case 'live-system-message':
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'live-update':
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'LoveChange':
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
						case 'updateMic':
							tim.setMessageRead({
								conversationID: event.data[i].conversationID,
							});
							uni.$emit('live_room-page', {
								type: event.data[i].payload.data,
								data: event.data[i]
							})
							break;
							case 'setMute':
								tim.setMessageRead({
									conversationID: event.data[i].conversationID,
								});
								uni.$emit('live_room-page', {
									type: event.data[i].payload.data,
									data: event.data[i]
								})
								break;
						default:
							uni.$emit('message-page', {
								type: 'message',
								data: event.data[i]
							})
							uni.$emit('im-page', {
								type: 'message',
								data: event.data[i]
							})
							break;
					}
				} else if (event.data[i].type == 'TIMGroupSystemNoticeElem') {
					
					tim.setMessageRead({
						conversationID: event.data[i].conversationID,
					});
					if (event.data[i].payload.operationType == 5) {
						uni.$emit('live_room-page', {
							type: 'quit'
						})
					}
				} else if (event.data[i].type == 'TIMGroupTipElem') {
					uni.$emit('live_room-page', {
						type: 'TIMGroupTipElem',
						data: event.data[i]
					})
				} else {
					if (event.data[i].conversationType == 'GROUP') {
						tim.setMessageRead({
							conversationID: event.data[i].conversationID,
						});
						uni.$emit('live_room-page', {
							type: 'message',
							data: event.data[i]
						})
					}
					uni.$emit('message-page', {
						type: 'message',
						data: event.data[i]
					})
					uni.$emit('im-page', {
						type: 'message',
						data: event.data[i]
					})
					if(event.data[i].payload.text=="您被系统禁止" && event.data[i].conversationID=='C2Cadmin'){
						uni.showToast({
							title: event.data[i].payload.text,
							position: 'bottom',
							icon: 'none'
						})
						uni.removeStorageSync('myInfo');
						uni.removeStorageSync('myInfo');
						uni.removeStorageSync('kefuid');
						
						uni.reLaunch({
							url: '../welcome/welcome'
						});
					}
				}
			}
		
		   
		});
		
		// 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
		tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
			
			// event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
			// event.data - 存储 Conversation 对象的数组 - [Conversation]
			console.log('会话列表更新更新数据：',event)
			
		});
		
		// 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
		tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
			// event.name - TIM.EVENT.GROUP_LIST_UPDATED
			// event.data - 存储 Group 对象的数组 - [Group]
		});
		
		// 收到自己或好友的资料变更通知
		tim.on(TIM.EVENT.PROFILE_UPDATED, function(event) {
			// event.name - TIM.EVENT.PROFILE_UPDATED
			// event.data - 存储 Profile 对象的数组 - [Profile]
		});
		
		// 收到黑名单列表更新通知
		tim.on(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
			
			// event.name - TIM.EVENT.BLACKLIST_UPDATED
			// event.data - 存储 userID 的数组 - [userID]
		});
		
		// 收到 SDK 发生错误通知，可以获取错误码和错误信息
		tim.on(TIM.EVENT.ERROR, function(event) {
			
			// event.name - TIM.EVENT.ERROR
			// event.data.code - 错误码
			// event.data.message - 错误信息
			console.log('==========>收到 SDK 发生错误通知', JSON.stringify(event))
		});
		tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
			// 收到 SDK 进入 not ready 状态通知，此时 SDK 无法正常工作
			// event.name - TIM.EVENT.SDK_NOT_READY
		});
		
		// 收到被踢下线通知
		tim.on(TIM.EVENT.KICKED_OUT, function(event) {
			
			// event.name - TIM.EVENT.KICKED_OUT
			// event.data.type - 被踢下线的原因
			//	- TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
			//	- TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
			//	- TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢（v2.4.0起支持）。
			console.log('==========>被踢下线 原因是', JSON.stringify(event))
			if (event.data.type == TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED) {
				uni.showToast({
					title: '登录过期，请重新登录',
					position: 'bottom',
					icon: 'none'
				})
				uni.removeStorageSync('myInfo');
				uni.reLaunch({
					url: '../welcome/welcome'
				});
			}
			if (event.data.type == TIM.TYPES.KICKED_OUT_MULT_ACCOUNT) {
				uni.showToast({
					title: '账户在其他设备登录',
					position: 'bottom',
					icon: 'none'
				})
				uni.removeStorageSync('myInfo');
				uni.removeStorageSync('myInfo');
				uni.removeStorageSync('kefuid');
				
				uni.reLaunch({
					url: '../welcome/welcome'
				});
			}
		});
		Vue.prototype.$tim = tim
		if (myInfo) {
			tim.login({
				userID: app.IDBEFORE + myInfo.id + '',
				userSig: myInfo.UserSig,
			}).then(imResponse => {
				console.log('IM 登录成功:', imResponse.data);
			}).catch(imError => {
				console.warn('IM 登录失败:', imError);
				uni.showToast({
					title: '登录失败',
					position: 'bottom',
					icon: 'none'
				});
			});
			uni.switchTab({
				url: '../home/home'
			});
		}
		uni.$on('main', data => {
			console.log('main文件种监听 main返回信息',data)
			if (data.type == 'dismissGroup') {
				tim.dismissGroup(data.data.groupID + '').then(imResponse => {
					console.log('解散群组成功:', imResponse.data);
				}).catch(imError => {
					console.warn('解散群组失败:', imError);
				});
			}
			if (data.type == 'quitGroup') {
				tim.quitGroup(data.data.groupID + '').then(imResponse => {
					console.log('退出群组成功:', imResponse.data);
				}).catch(imError => {
					console.warn('退出群组失败:', imError);
				});
			}
			if (data.type == 'sendCustomMessage') {
				let payload = {
					data: data.data.type,
					description: '',
					extension: data.data.custom_ext
				}
				let conversationType = TIM.TYPES.CONV_C2C;
				if (data.data.type == 'AgreeJoin') {
					payload.description = '专属相亲同意上麦'
				}
				if (data.data.type == 'KickedOut') {
					payload.description = '专属相亲踢人'
				}
				if (data.data.type == 'LovePrivate') {
					payload.description = '红娘/月老邀请你专属上麦'
				}
				if (data.data.type == 'joinAnchor') {
					payload.description = '申请非专属相亲上麦'
				}
				if (data.data.type == 'AgreeJoinAnchor') {
					payload.description = '非专属相亲同意上麦'
				}
				if (data.data.type == 'LivePublic') {
					payload.description = '红娘/月老邀请你非专属上麦'
				}
				if (data.data.type == 'gift') {
					payload.description = '礼物'
				}
				if (data.data.type == 'live-system-message') {
					payload.description = data.data.description
				}
				if (data.data.type == 'live-update') {
					payload.description = data.data.description
				}
				if (data.data.type == 'addFriend') {
					payload.description = '送礼物加好友'
				}
				if (data.data.type == 'LoveChange') {
					payload.description = '转专属房间'
				}
				if (data.data.type == 'updateMic') {
					payload.description = '更新麦位信息'
				}
				if (data.data.type == 'closeMic') {
					payload.description = '拉下麦'
				}
				if (data.data.type == 'setMute') {
					payload.description = '禁麦'
				}
				let message = null;
				if (!!data.data.groupID) {
					message = tim.createCustomMessage({
						to: data.data.groupID + '',
						conversationType: TIM.TYPES.CONV_GROUP,
						payload: payload
					});
				} else {
					message = tim.createCustomMessage({
						to: data.data.to_uid + '',
						conversationType: TIM.TYPES.CONV_C2C,
						payload: payload
					});
				}
				tim.sendMessage(message).then(imResponse => {
					console.log(payload.description, imResponse);
				}).catch(imError => {
					console.warn(payload.description, imError);
				});
			}
			if (data.type == 'sendTextMessage') {
				let conversationType = TIM.TYPES.CONV_C2C;
				if (!!data.data.groupID) {
					conversationType = TIM.TYPES.CONV_GROUP;
				}
				let message = tim.createTextMessage({
					to: data.data.to_id + '',
					conversationType: conversationType,
					payload: {
						text: data.data.content,
					}
				});
				tim.sendMessage(message).then(imResponse => {
					console.log('文本消息发送成功', imResponse);
				}).catch(imError => {
					console.warn('文本消息发送失败', imError);
				});
			}
			if (data.type == 'loginIM') {
				tim.login({
					userID: app.IDBEFORE + data.data.id + '',
					userSig: data.data.UserSig,
				}).then(imResponse => {
					console.log('IM 登录成功:', imResponse.data);
					uni.showToast({
						title: '登录成功',
						position: 'bottom',
						icon: 'none'
					});
				}).catch(imError => {
					console.warn('IM 登录失败:', imError);
					uni.showToast({
						title: '登录失败:' + JSON.stringify(imError),
						position: 'bottom',
						icon: 'none'
					});
				});
			}
		})
	} else {
		uni.showToast({
			title: res.msg,
			position: 'bottom',
			icon: 'none'
		});
	}
}, err => {
	uni.hideLoading();
	uni.showToast({
		title: '网络错误，请检查网络',
		position: 'bottom',
		icon: 'none'
	});
})

// 获取是否隐藏配置
api.api.ajaxData({
	method: 'V1.GetConfig',
	config: 'love.hidden',
},res=>{
	if (res.status) {
		uni.setStorage({
			key: 'isHidden',
			data: {
				isHidden: res.data,
			},
			success: res => {
			}
		})
		
	}
})
app.$mount()